const crypto = require('crypto');
const https = require('https');
const http = require('http');

export class Utils {


    /**
     * 64编码
     * @param value 
     */
    public static encoding64(value: string) {
        return new Buffer(value).toString();
    }

    /**
     * 64解码
     * @param value 
     */
    public static decode64(value: string) {
        return new Buffer(value, 'base64').toString();
    }


    /**
     * sha256 加密
     * @param value 
     */
    public static sha256(value) {
        let hash = crypto.createHash('sha256');
        hash.update(value)
        //  console.log(hash.digest('hex'));

        return hash.digest('hex');
    }

    /**
     * 获取字符串大小
     */
    public static getSize(value) {
        let realLength = 0, len = value.length, charCode = -1;
        for (let i = 0; i < len; i++) {
            charCode = value.charCodeAt(i);
            if (charCode >= 0 && charCode <= 128) realLength += 1;
            else realLength += 2;
        }
        return realLength;
    }

    /**
     * 字节转换
     * @param bytes 
     */
    public static bytesToSize(bytes) {
        if (bytes === 0) return '0 B';
        let k = 1024;
        let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        let i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)) + ' ' + sizes[i];                                                                 //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];  
    }


    /**
   * 创建随机字符串
   */
    public static getRandom(len?: number) {
        let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        let key = "";
        if (len == null || len == undefined) {
            len = 32;
        }
        for (let i = 0; i < len; i++) {
            let rand = parseInt(this.RandomNumBoth(0, 61));
            key += str[rand];//随机数  
        }
        return key;
    }

    /**
     * 生成指定范围的随机数
     * @param Min  最小值
     * @param Max  最大值
     */
    public static RandomNumBoth(Min, Max) {
        let Range = Max - Min;
        let Rand = Math.random();
        let num = Min + Math.round(Rand * Range); //四舍五入
        return num;
    }

    /**
    * 生成时间戳
    */
    public static getTimeStamp() {
        let timeTamp: number = Date.now() / 1000;
        return parseInt(timeTamp.toString());
    }


    /**
     * 获取当前时间
     */
    public static getNowFormatDate() {
        let date = new Date();
        let seperator1 = "-";
        let seperator2 = ":";
        let month = (date.getMonth() + 1).toString();
        let strDate = date.getDate().toString();
        if ( parseInt(month)  >= 1 && parseInt(month) <= 9) {
            month = "0" + month;
        }
        if (parseInt(strDate) >= 0 && parseInt(strDate) <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }


    /**
     * 获取指定网站的服务器时间
     * @param webUrl 
     */
    public static getWebsiteDatetime(webUrl: string) {
        return new Promise(function (resolve, reject) {
            http.get(webUrl, function (res) {
                let dateStr = res.headers.date;
                let date = new Date(dateStr);
                let timeTamp = Date.parse(date.toString()) / 1000;
                const { statusCode } = res;
                let error;
                // if (statusCode !== 200) {
                //     error = new Error('请求失败。\n' + `状态码: ${statusCode}`);
                // }
                if (error) {
                    console.error(error.message);
                    // 消耗响应数据以释放内存
                    res.resume();
                    reject(error);
                }
                else {
                    resolve(timeTamp);
                }
            });
        });
    }




    public static  excludeSpecial(s) {
        // 去掉转义字符
        s = s.replace(/[\'\"\\\/\b\f\n\r\t]/g, ''); 
        return s;
     };
     
}